import dbm
import time

db = dbm.open('tasks', 'c')

current_task_name = None
current_task_start_time = None

while True:
    command = input("请输入命令（'q' 退出，'l' 列出所有任务及其用时）或者输入任务名称开始新任务: ")

    if command == "q":
        break

    if command == "l":
        print("所有任务及其用时:")
        for task_name, task_start_time in db.items():
            task_name = task_name.decode()
            task_start_time = float(task_start_time.decode())

            if task_name == current_task_name:
                task_elapsed_time = int(time.time()) - int(task_start_time)
            else:
                task_elapsed_time = time.time() - task_start_time
            
            if task_elapsed_time > 0:
                print("任务名: {}, 用时: {}秒".format(task_name, task_elapsed_time))
            else:
                if task_name == current_task_name:
                    print("任务名: {}, 用时: 进行中".format(task_name))
                else:
                    print("任务名: {}, 用时: 尚未开始".format(task_name))
    else:
        if current_task_name is not None:
            current_task_elapsed_time = int(time.time()) - current_task_start_time
            if current_task_elapsed_time > 0:
                print("任务 '{}' 结束，用时 {} 秒".format(current_task_name, current_task_elapsed_time))
            
        current_task_name = command
        current_task_start_time = time.time()
        db[current_task_name.encode()] = str(current_task_start_time).encode()
        print("开始新任务: '{}'".format(current_task_name))
        
db.close()
